<?php

namespace Bean\Flow\PostsFlow;

class ContactsFlow extends \Bean\Flow\PostsFlow {

	private $_user;
	private $_posts = array();
	
	public function __construct( \Bean\User $user ) {
		parent::__construct( array() );
		$this->_user = $user;
	}

	public function getUser() {
		return $this->_user;
	}
	
	public function isReadable( \Bean\User $user = null ) {
		return $this->getUser()->is( $user )
			|| $this->getUser()->isContact( $user );
	}
	
	public function isPostable( User $user = null ) {
		return false;
	}

	public function getPosts( $i = 0 ) {

		if( !isset($this->_posts[$i]) ) {
			$start = (int) $i*self::N_ITEMS_BY_BLOCK;
			$size = self::N_ITEMS_BY_BLOCK;
			$query = 'SELECT *
				FROM posts up
				LEFT JOIN users u
				ON up.user_id = u.user_id
				WHERE up.user_id IN (SELECT contact_id
				FROM users_contacts uc
				WHERE uc.user_id = :user_id)
				OR up.user_id = :user_id
				ORDER BY publication_time DESC
				LIMIT ' . $start . ', ' . $size;
			$stmt = \Library\Database::getDb()->prepare( $query );
			$stmt->execute( array(
				':user_id' => $this->getUser()->getUserId()
			) );
			$posts = array();
			foreach( $stmt->fetchAll( \PDO::FETCH_ASSOC ) as $post ) {
				$posts[] = \Bean\Flow\PostsFlow\Item::get( $post['post_id'] );
			}
			$this->_posts[$i] = $posts;
		}

		return $this->_posts[$i];
	}
}
